/**
 *
 * Copyright by Samuel Castro & Joaquim Fonseca, 2011
 * All Rights Reserved
 *
 * NOTES:
 * Please do not redistribute this plugin without my permission
 * Plugin made for private use only
 *
 */
package com.SySammy.sdRankingSys;

import com.SySammy.sdRankingSys.Listeners.RPlayerListener;
import com.SySammy.sdRankingSy.PersistenceClasses.Players;
import com.SySammy.sdRankingSy.PersistenceClasses.Ranks;
import com.SySammy.sdRankingSys.Handlers.VocationHandler;
import com.SySammy.sdRankingSys.Listeners.sdEntityListener;
import com.SySammy.sdRankingSys.prop.sdRankProperties;
import com.nijiko.permissions.PermissionHandler;
import com.nijikokun.bukkit.Permissions.Permissions;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.persistence.PersistenceException;
import org.bukkit.entity.Player;
import org.bukkit.event.Event;
import org.bukkit.event.Event.Priority;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.PluginDescriptionFile;
import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.java.JavaPlugin;

public class sdRS extends JavaPlugin {

    private RPlayerListener PL = new RPlayerListener(this);
    private sdEntityListener EL = new sdEntityListener(this);
    public static sdRS plugin;
    private static final String RankDIR = "plugins/RPGmod/Rank/";
    private static final Logger log = Logger.getLogger("Minecraft");
    public PermissionHandler Permissions;
    private boolean UsePermissions;

    public static void main(String[] args) {
        // TODO code application logic here
    }

    @Override
    public void onLoad() {
        new File(RankDIR).mkdirs();
        File VocMaker = new File(RankDIR + "VocationMaker.yml");
        if (!VocMaker.exists()) {
            InputStream jarURL = getClass().getResourceAsStream("/VocationTemplate/VocationMaker.yml");
            try {
                copyFile(jarURL, new File(RankDIR + "VocationMaker.yml"));
            } catch (Exception ex) {
                Logger.getLogger(sdRS.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    @Override
    public void onDisable() {
        System.out.println("disabled, goodbye wold");
    }

    @Override
    public void onEnable() {
        PluginDescriptionFile pdfFile = this.getDescription();
        PluginManager pm = getServer().getPluginManager();
        sdRankProperties.loadMiningProps();
        setupPermissions();
        setupDatabase();
        getCommand("vocation").setExecutor(new sdRankCmds(this));
        getCommand("perks").setExecutor(new sdRankCmds(this));
        pm.registerEvent(Event.Type.PLAYER_JOIN, this.PL, Priority.Normal, this);
        pm.registerEvent(Event.Type.PLAYER_CHAT, this.PL, Priority.Normal, this);
        pm.registerEvent(Event.Type.ENTITY_DAMAGE, this.EL, Priority.Normal, this);
        pm.registerEvent(Event.Type.ENTITY_DEATH, this.EL, Priority.Normal, this);
        System.out.println(pdfFile.getName() + " version " + pdfFile.getVersion() + " is enabled!");
        plugin = this;

    }

    public static void copyFile(InputStream in, File out) throws Exception {
        InputStream fis = in;
        FileOutputStream fos = new FileOutputStream(out);
        try {
            byte[] buf = new byte[1024];
            int i = 0;
            while ((i = fis.read(buf)) != -1) {
                fos.write(buf, 0, i);
            }
        } catch (Exception e) {
            throw e;
        } finally {
            if (fis != null) {
                fis.close();
            }
            if (fos != null) {
                fos.close();
            }
        }
    }

    private void setupDatabase() {
        try {
            getDatabase().find(Players.class).findRowCount();
        } catch (PersistenceException ex) {
            System.out.println("Installing database for " + getDescription().getName() + " due to first time usage");
            installDDL();
        }
    }

    @Override
    public List<Class<?>> getDatabaseClasses() {
        List<Class<?>> list = new ArrayList<Class<?>>();
        list.add(Players.class);
        list.add(Ranks.class);
        return list;
    }

    private void setupPermissions() {
        Plugin test = this.getServer().getPluginManager().getPlugin("Permissions");

        if (this.Permissions == null) {
            if (test != null) {
                UsePermissions = true;
                this.Permissions = ((Permissions) test).getHandler();
                System.out.println("Permissions is enable for sdRankingSystem.");
            } else {
                log.info("Permission system not detected, defaulting to OP");
                UsePermissions = false;
            }
        }
    }

    public boolean canUseVocationStatus(Player p) {
        if (UsePermissions) {
            return this.Permissions.has(p, "vocation.status");
        }
        return p.isOp();
    }

    public boolean canUseVocationList(Player p) {
        if (UsePermissions) {
            return this.Permissions.has(p, "vocation.list");
        }
        return p.isOp();
    }

    public boolean canUseJoinVocation(Player p) {
        if (UsePermissions) {
            return this.Permissions.has(p, "vocation.join");
        }
        return p.isOp();
    }

    public boolean canUseVocationHelp(Player p) {
        if (UsePermissions) {
            return this.Permissions.has(p, "vocation.help");
        }
        return p.isOp();
    }

    public boolean canUsePerksStatus(Player p) {
        if (UsePermissions) {
            return this.Permissions.has(p, "perks.status");
        }
        return p.isOp();
    }

    public boolean canUsePerksList(Player p) {
        if (UsePermissions) {
            return this.Permissions.has(p, "perks.list");
        }
        return p.isOp();
    }

    public boolean canUsePerksAdd(Player p) {
        if (UsePermissions) {
            return this.Permissions.has(p, "perks.add");
        }
        return p.isOp();
    }

    public boolean canUsePerksRemove(Player p) {
        if (UsePermissions) {
            return this.Permissions.has(p, "perks.remove");
        }
        return p.isOp();
    }

    public boolean canUsePerksHelp(Player p) {
        if (UsePermissions) {
            return this.Permissions.has(p, "perks.help");
        }
        return p.isOp();
    }

    public static void AddExp(Player p, int exp) {
        VocationHandler VH = new VocationHandler(plugin);
        VH.AddExp(p, exp);
    }
}
